﻿using System;
using Fly.Data;
using FlyWebFrame.Model;

namespace FlyWebFrame.Action
{
    public class search : homeaction
    {
        public string client_script;
        public string search_script = "";
        
        public int lastindex;
        public int nextindex;
        public int preindex;
        public int pageindexview;
        public int countpage;
        public int countresult;
        public string key = "";
        public dynamic searchresult;

        public override void Treat()
        {
            page_title += " - Kết quả tìm kiếm";
            
            if (Form["submitSearch"] == "true")
            {
                // get search result
                int pageindex;

                Int32.TryParse(GetParameter(1), out pageindex);
                pageindexview = pageindex + 1;

                key = Form["txtSearch"];
                News news = new News();
                searchresult = news.Search(key, pageindex, 20).Data;
                search_script += "searchresult = '" + Fly.Util.Serializer.Json.Encode(searchresult) + "';";
                countpage = news.CountPageSearch(key, 20);

                if (searchresult != null)
                {
                    for (int k = 0; k < searchresult.Length; k++)
                    {
                        searchresult[k].Date = searchresult[k].Since.Hour.ToString() + ":" + searchresult[k].Since.Minute.ToString() + " | " + searchresult[k].Since.Day.ToString() + '/' + searchresult[k].Since.Month.ToString() + '/' + searchresult[k].Since.Year.ToString();
                        searchresult[k].Title = searchresult[k].Title.ToString().Replace("\"", "\\\"");
                        search_script += "searchresult = '" + Fly.Util.Serializer.Json.Encode(searchresult) + "';";
                    }
                    if (searchresult.Length < 20) countresult = searchresult.Length;
                    else countresult = searchresult.Length * countpage;
                }

                if (countpage > 1)
                {
                    client_script += "$('#search-paging').removeClass('hidden')";
                    if (pageindex >= countpage - 1)
                    {
                        nextindex = pageindex;
                    }
                    else
                    {
                        nextindex = pageindex + 1;
                    }
                    if (pageindex == 0)
                    {
                        preindex = 0;
                    }
                    else
                    {
                        preindex = pageindex - 1;
                    }
                    lastindex = countpage - 1;
                }
            }
        }
    }
}